package com.dq.utils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cf
 *
 * list  工具类
 */
public class ListUtils {

    /**
     * 判断一个字符串是否在一个list, 在返回角标
     */
    public static int listIn(String key, List<String> list) {
        if(StringUtils.isNotBlank(key)) {
            for (int i = 0; i < list.size(); i++) {
                String s = list.get(i);
                if(key.equals(s)) {
                    return i;
                }
            }
        }
        return -1;
    }
    /**
     * 判断是否在list, 在返回角标
     */
    public static int listIn(Object key, List list) {
        if(key != null) {
            for (int i = 0; i < list.size(); i++) {
                Object s = list.get(i);
                if(key.toString().equals(s.toString())) {
                    return i;
                }
            }
        }
        return -1;
    }

    /**
     * list 深拷贝
     */
    public static List copyList(List oldList) {
        List newList = new ArrayList<>();
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        try {
            ObjectOutputStream out = new ObjectOutputStream(byteOut);
            out.writeObject(oldList);

            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream inStream = new ObjectInputStream(byteIn);
            newList = (List) inStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return newList;
    }
}
